<template>
	<div class="spec-preview">
		<img :src="skuImageList[curIndex].imgUrl" />
		<!-- 图片上的专门用来获取坐标的盒子 -->
		<div class="event" ref="eveDiv" @mousemove="mouseMove">
			{{ XX }},{{ YY }}
		</div>
		<div class="big">
			<img :src="skuImageList[curIndex].imgUrl" ref="big" />
		</div>
		<!-- 遮罩层 -->
		<div class="mask" ref="mask"></div>
	</div>
</template>

<script>
import throttle from "lodash/throttle";
export default {
	name: "Zoom",
	/* 	props: {
		skuImageList: {
			default() {
				return [{}];
			},
		},
	}, */
	props: ["skuImageList"],
	data() {
		return {
			curIndex: 0,
			XX: 0,
			YY: 0,
		};
	},
	/* 	created() {
		console.log(this.skuImageList);
	}, */
	mounted() {
		// 等着兄弟组件把点击图片的下标传来
		this.$bus.$on("postImgIndex", (index) => {
			this.curIndex = index;
		});
	},
	methods: {
		mouseMove: throttle(function (eve) {
			// 鼠标在图片上的坐标
			this.XX = eve.offsetX;
			this.YY = eve.offsetY;

			const mask = this.$refs.mask;
			const big = this.$refs.big;
			const eveDiv = this.$refs.eveDiv;
			// 遮罩层盒子自身的完整宽高
			// console.log(mask.offsetWidth, mask.offsetHeight);

			// 遮罩层跟随鼠标
			let Mleft = eve.offsetX - mask.offsetWidth / 2;
			let Mtop = eve.offsetY - mask.offsetHeight / 2;

			// x轴方向限制
			if (Mleft < 0) Mleft = 0;
			if (Mleft > eveDiv.offsetWidth - mask.offsetWidth)
				Mleft = eveDiv.offsetWidth - mask.offsetWidth;

			// y轴方向限制
			if (Mtop < 0) Mtop = 0;
			if (Mtop > eveDiv.offsetHeight - mask.offsetHeight)
				Mtop = eveDiv.offsetHeight - mask.offsetHeight;

			// 把计算好的值给遮罩层
			mask.style.top = Mtop + "px";
			mask.style.left = Mleft + "px";

			// 让右侧放大的图片 以两倍关系跟随
			big.style.top = -2 * Mtop + "px";
			big.style.left = -2 * Mleft + "px";
		}, 50),
	},
};
</script>

<style lang="less">
.spec-preview {
	position: relative;
	width: 400px;
	height: 400px;
	border: 1px solid #ccc;

	img {
		width: 100%;
		height: 100%;
	}

	.event {
		width: 100%;
		height: 100%;
		position: absolute;
		top: 0;
		left: 0;
		z-index: 998;
	}

	.mask {
		width: 50%;
		height: 50%;
		background-color: rgba(0, 255, 0, 0.3);
		position: absolute;
		left: 0;
		top: 0;
		display: none;
	}

	.big {
		width: 100%;
		height: 100%;
		position: absolute;
		top: -1px;
		left: 100%;
		border: 1px solid #aaa;
		overflow: hidden;
		z-index: 998;
		display: none;
		background: white;

		img {
			width: 200%;
			max-width: 200%;
			height: 200%;
			position: absolute;
			left: 0;
			top: 0;
		}
	}

	.event:hover ~ .mask,
	.event:hover ~ .big {
		display: block;
	}
}
</style>
